/**
 * 飞蛾打印机排版
 */
import moment from 'moment'
import iconv from 'iconv-lite'
import { ORDER_TYPE } from '../common/constants';

// import { substring } from 'sequelize/types/lib/operators'
// import { Stream } from 'stream'

export type PrintEle = {
    name: string
    price: number
    num: number
    // total: number
}

// 增加空格
function addSpace(str: string, size: number) {
    return [...str.split(''), ...Array.from({ length: size - str.length }).fill(' ')].join('')
}

const BASIC_LEN = {
    title: 14,
    price: 6,
    num: 3,
    total: 6
}

function getLen(str: string) {
    return iconv.decode(new Buffer(str), 'GBK').length
}

export function layout(printEles: PrintEle[], title: string, params) {

    const { order_type, meal_number, name } = params;
    const [INSTORE, TAKEOUT] = ORDER_TYPE;
    let bufferStr: string[] = [];
    // 堂食订单 有桌号
    if (order_type === INSTORE) {
        bufferStr.push(`<CB>取餐号:${meal_number}</CB><RIGHT>${title}</RIGHT><BR>`);
    }
    // 外卖订单
    if (order_type === TAKEOUT) {
        bufferStr.push(`<CB>${name}</CB><BR>`);
    }


    bufferStr.push('名称           单价  数量 金额<BR>')

    let i = 0;
    let t0 = 0
    console.log(printEles)
    while (i < printEles.length) {
        const { price, name, num } = printEles[i]
        let pstr = name
        const otherStr = ` ${addSpace(`${price}`, BASIC_LEN.price)}${addSpace(`${num}`, BASIC_LEN.num)} ${addSpace(`${price * num}`, BASIC_LEN.total)}`

        t0 += price * num * 100
        // 名称长度
        const titleLen = getLen(name)
        // 空格数量
        const spaceNum = (titleLen / BASIC_LEN.title + 1) * BASIC_LEN.title - titleLen

        console.log('---->', titleLen, spaceNum)
        if (titleLen < BASIC_LEN.title) {
            //  bufferStr.push(addSpace(name, spaceNum))
            // pstr += titleAddSpace(name)
            for (let k = 0; k < BASIC_LEN.title - titleLen - 1; k++) {
                pstr += ' '
            }
            pstr += otherStr
        } else if (titleLen === BASIC_LEN.title) {
            pstr += otherStr
        } else {
            // 长度大于本身的长度 应该换行

            let strlist: string[] = []
            //英文
            if (titleLen === name.length) {
                strlist = getStrs(name, BASIC_LEN.title)
            } else {
                strlist = getStrs(name, BASIC_LEN.title / 2)
            }
            let s0 = titleAddSpace(strlist[0])
            pstr = s0 + otherStr
            const s = getStrByEnter(BASIC_LEN.title, strlist.slice(1).join(''))
            pstr += s
        }

        bufferStr.push(`${pstr}<BR>`)
        i += 1
    }

    console.log(t0);
    layoutFooter(bufferStr, params)
    return bufferStr
}

function layoutFooter(pbuffer: string[], {
    note, phone, address, order_type, table_cost, pack_cost, all_price }) {

    pbuffer.push('--------------------------------<BR>')
    const [INSTORE, TAKEOUT] = ORDER_TYPE;
    if (order_type === INSTORE) {
        pbuffer.push(`餐具费：${table_cost / 100 || '-'}<BR>`)
    }
    if (order_type === TAKEOUT) {
        pbuffer.push(`打包费：${pack_cost / 100 || '-'}<BR>`)
    }

    pbuffer.push(`合计：${all_price / 100}元<BR>`)

    if (order_type === TAKEOUT) {
        pbuffer.push(`送货地点：${address || '-'}<BR>`)
        pbuffer.push(`联系电话：${phone || '-'} <BR>`)
    }

    pbuffer.push(`下单时间：${moment().format('YYYY-MM-DD HH-MM')}<BR>`)
    pbuffer.push(`备注：${note || '-'}<BR>`)
    // pbuffer.push('<QR>http://www.feieyun.com</QR>')
}

function titleAddSpace(title: string) {
    let k = 0
    let b = 14
    //   let str = title
    k = getLen(title)
    return addSpace(title, b - k)
}

function getStrs(str: string, len: number) {

    let size = str.length / len
    if (str.length % len !== 0) {
        size += 1
    }
    return getStrsBySize(str, len, size)
}

function getStrsBySize(str: string, len: number, size: number) {
    let i = 0;
    const strs: string[] = []
    while (i < size) {
        strs.push(substr(str, i * len, (i + 1) * len))
        i += 1
    }
    return strs
}

function substr(str: string, f: number, to: number) {
    if (f > str.length) {
        return ''
    }
    if (to > str.length) {
        return str.substring(f, str.length)
    } else {
        return str.substring(f, to)
    }
}

function getStrByEnter(len: number, str: string) {

    for (let i = 1; i <= str.length; i++) {
        if (getLen(str) > len) {
            return str.substring(0, i - 1) + "<BR>" + getStrByEnter(len, str.substring(i - 1));
        }
    }
    return str;
}